package cn.edu.seu.cose.qol.model.dao.config;

import java.io.IOException;

import cn.edu.seu.cose.qol.util.EnvironmentVariable;


public class BasicConfigAccessImpl implements BasicConfigAccess {
	
	private static final String BASIC_CONFIG_PROPERTIES_FILE_PATH =
			"config\\basic_config.properties";
	
	private static final String ID_PAGE_CAPACITY =
			"basic.questionnaire.style.page.capacity";
	
	private static final String ID_PAGE_MODE =
			"basic.questionnaire.style.page.mode";
	
	private static BasicConfigAccess _singleton;
	
	private PropertiesReader _reader;
	
	private PropertiesWriter _writer;
	
	private String _webContentPath;
	
	public static synchronized BasicConfigAccess getInstance()
			throws IOException {
		if (_singleton == null) {
			EnvironmentVariable eV = EnvironmentVariable.getInstance();
			String webContentPath = eV.get(EnvironmentVariable.REAL_PATH);
			_singleton = new BasicConfigAccessImpl(webContentPath);
		}
		
		return _singleton;
	}
	
	protected BasicConfigAccessImpl(String webContentPath) throws IOException {
		_webContentPath = webContentPath;
		
		String realPath = webContentPath + BASIC_CONFIG_PROPERTIES_FILE_PATH;
		_reader = PropertiesReader.getInstance(realPath);
		_writer = PropertiesWriter.getInstance(realPath);
	}
	
	@Override
	public void setPageCapacity(int capacity) throws IOException {
		String pageCapacityInString = new Integer(capacity).toString();
		_writer.setProperty(ID_PAGE_CAPACITY, pageCapacityInString);
	}

	@Override
	public int getPageCapacity() throws IllegalArgumentInConfigFileException {
		try {
			String pageCapacityInString = _reader.getProperty(ID_PAGE_CAPACITY);
			int pageCapacity = new Integer(pageCapacityInString);
			return pageCapacity;
		} catch (NumberFormatException e) {
			throw new IllegalArgumentInConfigFileException(ID_PAGE_CAPACITY);
		}
	}

	@Override
	public void setPageMode(PageMode mode) throws IOException {
		String pageModeInString = mode.name().toLowerCase();
		_writer.setProperty(ID_PAGE_MODE, pageModeInString);
	}

	@Override
	public PageMode getPageMode() throws IllegalArgumentInConfigFileException {
		String pageModeInString = _reader.getProperty(ID_PAGE_MODE);
		pageModeInString = pageModeInString.trim().toUpperCase();
		PageMode pageMode = PageMode.valueOf(pageModeInString);
		
		if (pageMode == null) {
			throw new IllegalArgumentInConfigFileException(ID_PAGE_CAPACITY);
		}
		
		return pageMode;
	}
	
	protected final String getWebContentPath() {
		return _webContentPath;
	}

}
